//
//  UITextFieldViewController.swift
//  Example
//
//  Created by T AO on 2022/2/15.
//

import UIKit
import RxCocoa
import RxSwift

class UITextFieldViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

//        textField1()
//        textField()
//        moreTextField()
        event()
    }

}

// MARK: - UITextField

extension UITextFieldViewController {
    /// 将 textField 里输入的内容实时地显示到控制台中
    private func textField1() {
        let textField = UITextField(frame: CGRect(x: 10, y: 80, width: 200, height: 30))
        textField.borderStyle = .roundedRect
        view.addSubview(textField)
        
        // 当文本框内容改变时，将内容输出到控制台上
        textField.rx.text
            .orEmpty // .orEmpty 可以将 String? 类型的 ControlProperty 转成 String，省得我们再去解包
            .asObservable()
            .subscribe(onNext: { print("输入的是：\($0)") })
            .disposed(by: disposeBag)
        
        // 另一种写法: 直接使用 change 事件效果也是一样的
        textField.rx.text
            .orEmpty
            .changed
            .subscribe(onNext: { print("输入的是2：\($0)") })
            .disposed(by: disposeBag)
    }
    
    /// 将内容绑定到其它控件上
    private func textField() {
        let inputTextField = UITextField(frame: CGRect(x: 10, y: 150, width: 200, height: 30))
        inputTextField.borderStyle = .roundedRect
        view.addSubview(inputTextField)
        
        let outputTextField = UITextField(frame: CGRect(x: 10, y: 200, width: 200, height: 30))
        outputTextField.borderStyle = .roundedRect
        view.addSubview(outputTextField)
        
        let label = UILabel(frame: CGRect(x: 20, y: 300, width: 300, height: 30))
        view.addSubview(label)
        
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 20, y: 400, width: 40, height: 30)
        button.setTitle("提交", for: .normal)
        view.addSubview(button)
        
        // 当文本框内容改变
        let input = inputTextField.rx.text
            .orEmpty
            .asDriver() // 将普通序列转换为 Driver
            .throttle(RxTimeInterval.milliseconds(300)) // 在主线程中操作，0.3秒内值若多次改变，取最后一次
        
        // 内容绑定到另一个文本框中
        input
            .drive(outputTextField.rx.text)
            .disposed(by: disposeBag)
        
        // 内容绑定到 label 中
        input
            .map { "当前字数：\($0.count)" }
            .drive(label.rx.text)
            .disposed(by: disposeBag)
        
        // 根据内容字数决定按钮是否可用
        input
            .map { $0.count > 5 }
            .drive(button.rx.isEnabled)
            .disposed(by: disposeBag)
    }
    
    /// 同时监听多个 textField 内容的变化
    private func moreTextField() {
        let oneTextField = UITextField(frame: CGRect(x: 10, y: 150, width: 200, height: 30))
        oneTextField.borderStyle = .roundedRect
        oneTextField.placeholder = "区号"
        view.addSubview(oneTextField)
        
        let twoTextField = UITextField(frame: CGRect(x: 10, y: 200, width: 200, height: 30))
        twoTextField.borderStyle = .roundedRect
        twoTextField.placeholder = "号码"
        view.addSubview(twoTextField)
        
        let label = UILabel(frame: CGRect(x: 10, y: 250, width: 300, height: 30))
        view.addSubview(label)
        
        Observable.combineLatest(oneTextField.rx.text.orEmpty, twoTextField.rx.text.orEmpty) { value1, value2 in
            return "您输入的号码是：\(value1)-\(value2)"
        }
        .map { $0 }
        .bind(to: label.rx.text)
        .disposed(by: disposeBag)
    }
    
    /// 事件监听
    /// （1）通过 rx.controlEvent 可以监听输入框的各种事件，且多个事件状态可以自由组合。除了各种 UI 控件都有的 touch 事件外，输入框还有如下几个独有的事件：
    ///
    /// editingDidBegin：开始编辑（开始输入内容）
    /// editingChanged：输入内容发生改变
    /// editingDidEnd：结束编辑
    /// editingDidEndOnExit：按下 return 键结束编辑
    /// allEditingEvents：包含前面的所有编辑相关事件
    ///
    private func event() {
        let username = UITextField(frame: CGRect(x: 10, y: 150, width: 200, height: 30))
        username.borderStyle = .roundedRect
        username.placeholder = "用户名"
        view.addSubview(username)
        
        let password = UITextField(frame: CGRect(x: 10, y: 200, width: 200, height: 30))
        password.borderStyle = .roundedRect
        password.placeholder = "密码"
        view.addSubview(password)
        
        // 在用户名输入框中按下 return 键
        username.rx.controlEvent(.editingDidEndOnExit)
            .subscribe(onNext: { password.becomeFirstResponder() })
            .disposed(by: disposeBag)
        
        // 在密码输入框中按下 return 键
        password.rx.controlEvent(.editingDidEndOnExit)
            .subscribe(onNext: { password.resignFirstResponder() })
            .disposed(by: disposeBag)
        
        // 状态可以组合
        password.rx.controlEvent([.editingDidBegin, .editingChanged])
            .asObservable()
            .subscribe { event in
                print("输入密码：\(event)")
            }
            .disposed(by: disposeBag)
    }
}
